//
//  SCTestReportUploadVC.m
//  Shuaiche
//
//  Created by yujunyang on 2021/4/28.
//  Copyright © 2021 ShuaiChe. All rights reserved.
//

#import "SCTestReportUploadVC.h"
#import "TZImagePickerController.h"
#import "SCHttpManager.h"
#import <UIButton+WebCache.h>
#import "SCImageUploadManager.h"
#import "MBProgressHUD+Add.h"
#import "Config.h"
#import "NSString+Helper.h"
#import "SCMaintUploadCollecCell.h"
#import "SCModel.h"
#import "SCCollectionViewColorFlowLayout.h"
#import "SCComplaintHeaderView.h"
#import "SCFormModel.h"
#import <Masonry.h>
#import "SCDynamicSegmentView.h"
#import "SCMaintUploadPdfHeaderView.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "SCFileManager.h"
#import "SCWebViewController.h"
#import "SCReportPdfModel.h"
#import "MJPhotoBrowser.h"
#define SegmentHeight 45
#define HeaderHeight 75

@interface SCTestReportUploadVC ()<SCMaintUploadCollecCellDelegate,TZImagePickerControllerDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIDocumentPickerDelegate,SCDynamicSegmentViewDelegate>

@property (nonatomic, strong) NSMutableArray *imgArray;
@property (nonatomic, assign) NSInteger maxCount;
@property (nonatomic, strong) UIButton *uploadBtn;
@property (nonatomic, copy) NSString *reportUrl;
@property (strong, nonatomic) UIDocumentPickerViewController *documentPickerVC;
@property (strong, nonatomic) SCDynamicSegmentView *segmengView;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) NSArray *headerHeight;
@property (nonatomic, strong) SCReportPdfModel *pdfModel;

@end

@implementation SCTestReportUploadVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor whiteColor];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
  if (_uploadType == SCReportUploadCarContract) {
    self.segmengView.titles = @[@"PDF",@"合同截图"];
  } else {
    self.segmengView.titles = @[@"PDF",@"第三方链接",@"报告截图"];
  }
  
    [self.segmengView selectedAtIndex:0];
    SCMaintUploaldTipView *tipView = [SCMaintUploaldTipView new];
    [self.view addSubview:tipView];
    [tipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(45);
        make.height.mas_equalTo(30);
    }];
    
    [self configureDataSource];
    [self.view addSubview:self.uploadBtn];
    [self.uploadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@10);
        make.right.equalTo(@-10);
        make.bottom.equalTo(@(-kSCScreenBottomOffset));
        make.height.mas_equalTo(SegmentHeight);
    }];
    if (_uploadType == SCReportUploadMaintenance) {
        self.navigationItem.title = @"上传维保报告";
        
    }else if (_uploadType == SCReportUploadCarDetection) {
        self.navigationItem.title = @"上传检测报告";
    }else if (_uploadType == SCReportUploadCarContract) {
      self.navigationItem.title = @"上传合同";
    }
    _pdfModel = [SCReportPdfModel new];
    [self configuraPreParams];
   
}

- (void)configureDataSource {
    _imgArray = [NSMutableArray arrayWithCapacity:0];
    [_imgArray addObject:[SCCarAddImageItemModel addModel]];
    _maxCount = 30;
    
    if (_uploadType == SCReportUploadCarContract) {
      self.headerHeight = @[@(176),@(44)];
    } else {
      self.headerHeight = @[@(176),@(80),@(44)];
    }
    
    SCFormSectionModel *section = [[SCFormSectionModel alloc] init];
    section.sectionKey = @"pdf";
    section.headerHeight = [self.headerHeight[0] intValue];
    [self.dataSource addObject:section];
    
    if (_uploadType != SCReportUploadCarContract) {
      section = [[SCFormSectionModel alloc] init];
      section.sectionKey = @"url";
      //    section.headerHeight = 165;
      [self.dataSource addObject:section];
    }
  
    section = [[SCFormSectionModel alloc] init];
    section.sectionKey = @"img";
//    section.headerHeight = 44;
  section.headerTitle = _uploadType == SCReportUploadMaintenance ? @"维保报告截图" : (_uploadType == SCReportUploadCarDetection ? @"检测报告截图":@"合同截图");
    [section.rows addObjectsFromArray:_imgArray];
    [self.dataSource addObject:section];
    // 添加长按抖动手势
    [self addGesture];
}

#pragma mark -添加手势-
- (void)addGesture
{
    UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];
    [self.collectionView addGestureRecognizer:longGesture];
}

// 长按抖动手势方法
- (void)handlelongGesture:(UILongPressGestureRecognizer *)longGesture {
    switch (longGesture.state) {
        case UIGestureRecognizerStateBegan:{
        
            // 通过手势获取点，通过点获取点击的indexPath， 移动该cell
            NSIndexPath *aIndexPath = [self.collectionView indexPathForItemAtPoint:[longGesture locationInView:self.collectionView]];
            if (aIndexPath.row == _imgArray.count-1) {
                return;
            }
            [self.collectionView beginInteractiveMovementForItemAtIndexPath:aIndexPath];
            
        }
            break;
        case UIGestureRecognizerStateChanged:{
            
            NSIndexPath *aIndexPath = [self.collectionView indexPathForItemAtPoint:[longGesture locationInView:self.collectionView]];
            if (aIndexPath.row == _imgArray.count - 1) {
                return;
            }
            if (aIndexPath) {
                // 通过手势获取点，通过点获取拖动到的indexPath， 更新该cell位置
                [self.collectionView updateInteractiveMovementTargetPosition:[longGesture locationInView:self.collectionView]];
            }
        }
            break;
        case UIGestureRecognizerStateEnded:{
        
            // 移动完成关闭cell移动
            [self.collectionView endInteractiveMovement];
        }
            break;
        default:
            [self.collectionView endInteractiveMovement];
            break;
    }
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    if (sourceIndexPath.row == _imgArray.count-1) {
        return;
    }
    // 删除数据源中初始位置的数据
    id objc = [_imgArray objectAtIndex:sourceIndexPath.item];
    [_imgArray removeObject:objc];

    // 将数据插入数据源中新的位置，实现数据源的更新
    [_imgArray insertObject:objc atIndex:destinationIndexPath.item];

}

- (void)configuraPreParams{
    _preImage = _preParams[@"reportPic"];
    _reportUrl = _preParams[@"reportPcUrl"];
    _pdfModel.reportPdf = _preParams[@"reportPdf"];
    _pdfModel.showFile = [_preParams[@"reportPdf"] length]>0?YES:NO;
    if (_preImage.length > 0 || _reportUrl.length > 0) {
        if (_preImage.length > 0) {
            NSArray *urls = [_preImage componentsSeparatedByString:@","];
            self.preImage = urls.firstObject;
            [self.imgArray removeAllObjects];
            for (int i = 0; i < urls.count; i++) {
                SCCarAddImageItemModel *model = [[SCCarAddImageItemModel alloc] init];
                model.imageUrlPath = urls[i];
                [self.imgArray addObject:model];
                if (i > 0) {
                    self.preImage =  [self.preImage stringByAppendingString:[@"," stringByAppendingString:urls[i]]];
                }
            }
            [self.imgArray addObject:[SCCarAddImageItemModel addModel]];
        } else {
        }
        return;
    }
    if (_uploadType == SCReportUploadMaintenance) {
        [self fetchRecentlyRecord];
    }
}

#pragma mark- 获取最近一条维保记录
- (void)fetchRecentlyRecord {
    if (_vcode) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:_vcode forKey:kVcode];
      [[SCHttpManager shareInstance] httpGet:@"/stockprod/maintenanceRecord/byVinNew" param:dic completion:^(id response, NSError *error){
        if (error) {
            
        }else {
            if (response) {
                NSArray *urls = response[@"reportPics"];
                self.preImage = urls.firstObject;
                [self.imgArray removeAllObjects];
                for (int i = 0; i < urls.count; i++) {
                    SCCarAddImageItemModel *model = [[SCCarAddImageItemModel alloc] init];
                    model.imageUrlPath = urls[i];
                    [self.imgArray addObject:model];
                    if (i > 0) {
                        self.preImage =  [self.preImage stringByAppendingString:[@"," stringByAppendingString:urls[i]]];
                    }
                }
                [self.imgArray addObject:[SCCarAddImageItemModel addModel]];
                self.reportUrl = response[@"reportPcUrl"];
                //维保pdf
                _pdfModel.reportPdf = response[@"reportPdf"];
                _pdfModel.showFile = [_pdfModel.reportPdf length]>0?YES:NO;
            }
        }
        [self.collectionView reloadData];
        
    }];
    }
}

#pragma mark- 上传按钮点击事件
- (IBAction)uploadButtonClick:(UIButton *)sender {
    
    if ([NSString SC_isBlankString:_reportUrl] && (_imgArray.count == 1)&&_pdfModel.md5filePath.length == 0 && _pdfModel.reportPdf.length == 0) {
      NSString *msg = _uploadType == SCReportUploadMaintenance ? @"请上传PDF文件或维保报告链接或者截图" : (_uploadType == SCReportUploadCarDetection ? @"请上传PDF文件或检测报告链接或者截图":@"请上传PDF文件或电子合同链接或者截图");
        [MBProgressHUD showTip:msg];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showMessage:@"正在上传" toView:nil];
    if (_reportUrl.length) { // 报告链接http判断
        if (![_reportUrl hasPrefix:@"http"]) {
            _reportUrl = [@"https://" stringByAppendingString:_reportUrl];
        }
        [[SCHttpManager shareInstance] httpGetUrlValid:_reportUrl completion:^(BOOL valid) {
            if (valid) {
                [self imageUpload:hud];
            }else{
                [hud switchShowError:@"填写地址无效，请填写正确的报告地址"];
                if (_selectIndex != 1) {
                    [self segmentDidClickedAtIndex:1];
                }
            }
        }];
        
    }else{
        [self imageUpload:hud];
    }
}

#pragma mark- 图片上传
- (void)imageUpload:(MBProgressHUD *)hud{
    
    NSMutableArray *imageArray = [_imgArray mutableCopy];
    SCCarAddImageItemModel *itemModel = imageArray.lastObject;
    if (itemModel.isAddButton) {
        [imageArray removeLastObject];
    }
    WEAKSELF
    if (imageArray) {
        [SCImageUploadManager startUploadImages:imageArray completion:^(NSArray * _Nonnull picUrls,NSString *errorString) {
            if (picUrls) {
                weakSelf.preImage = picUrls.firstObject;
                for (int i = 1; i < picUrls.count; i++) {
                    weakSelf.preImage =  [weakSelf.preImage stringByAppendingString:[@"," stringByAppendingString:picUrls[i]]];
                }
                [weakSelf pdfUpload:hud];
            } else {
                [hud switchShowError:@"图片上传失败"];
            }
        }];
    }
    else {
        [self pdfUpload:hud];
    }
}

#pragma mark- pdf文件上传
- (void)pdfUpload:(MBProgressHUD *)hud{
    if (_pdfModel.md5filePath.length > 0 &&_pdfModel.fileData.length > 0) {
        [SCImageUploadManager uploadingWithFileData:_pdfModel.fileData filePath:_pdfModel.md5filePath uploadType:_uploadType completion:^(NSString * _Nonnull filePath) {
            if (filePath.length > 0) {
                _pdfModel.reportPdf = sc_url_img(filePath);
                [SCFileManager deletePDFFile:_uploadType];
                [self uploadReport:hud];
            }else{
                [hud switchShowError:@"pdf上传失败"];
            }
        }];
    }else{
        //取得服务器url
        [self uploadReport:hud];
    }
}

#pragma mark-上传报告
- (void)uploadReport:(MBProgressHUD *)hud {
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
    if (_preImage) {
        [params setValue:_preImage forKey:@"reportPic"];
    }else{
        [params setValue:@"" forKey:@"reportPic"];
    }
    if (_reportUrl.length) { // 报告链接http判断
        if (![_reportUrl hasPrefix:@"http"]) {
            _reportUrl = [@"http://" stringByAppendingString:_reportUrl];
        }
        [params setValue:_reportUrl forKey:@"reportPcUrl"];
    }else{
        [params setValue:@"" forKey:@"reportPcUrl"];
    }
    if (_pdfModel.reportPdf.length) {
        [params setValue:_pdfModel.reportPdf forKey:@"reportPdf"];
    }else{
        [params setValue:@"" forKey:@"reportPdf"];
    }
    
    [params setValue:_vcode forKey:kVcode];
    if (!_carId) { // 发车/车辆编辑
        [hud hide:YES];
        if (self.upload) {
            self.upload(params);
        }
        [self popViewController];
        return;
    }
    [params setValue:_carId forKey:kCarId];
  [params setValue:@([Config sharedConfig].user.userId) forKey:kUserId];
  [[SCHttpManager shareInstance] httpPost:@"stockprod/car/insertMerchantMaintenanceRecord" param:params completion:^(id response, NSError *error){
    if (error) {
        [hud switchShowError:error.localizedDescription];
    } else {
        [hud hide:YES];
        [self.navigationController popViewControllerAnimated:YES];
        if (self.upload) {
            self.upload(@{});
        }
    }
}];
}

#pragma mark- 返回
- (void)popViewController {
    NSArray *array = self.navigationController.viewControllers;
    int stop = 0;
    for (int i = (int)array.count - 1; i >= 0 ;i--) {
        UIViewController *vc = array[i];
        if ([vc isKindOfClass:NSClassFromString(@"SCCarMaintenReportVC")]) {
            stop = i;
            break;
        }
    }
    if (stop >= 1) {
        UIViewController *vc = array[stop - 1];
        [self.navigationController popToViewController:vc animated:YES];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark-
#pragma mark- 图片选择弹窗
- (void)showActionSheet {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选取图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
   
    [alert addAction:[UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showCamera];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showPhotoAlume];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark- 打开相机
- (void)showCamera {
    [self dismissViewControllerAnimated:NO completion:nil];
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        // picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

#pragma mark- 打开相册
- (void)showPhotoAlume {
    NSInteger count = _maxCount + 1 - _imgArray.count;
    TZImagePickerController *imagePickController = [[TZImagePickerController alloc] initWithMaxImagesCount:count delegate:self];
//    imagePickController.minImagesCount = 1;
    //是否 在相册中显示拍照按钮
    imagePickController.allowTakePicture = NO;
    //是否可以选择显示原图
    imagePickController.allowPickingOriginalPhoto = YES;
    //是否 在相册中可以选择视频
    imagePickController.allowPickingVideo = NO;
    imagePickController.showSelectBtn = YES;
    imagePickController.naviBgColor = [UIColor whiteColor];
    imagePickController.naviTitleColor = [UIColor blackColor];
    imagePickController.barItemTextColor = [UIColor blackColor];
    imagePickController.statusBarStyle = UIStatusBarStyleDefault;
    imagePickController.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePickController.navLeftBarButtonSettingBlock = ^(UIButton *lefyButton){
        [lefyButton setImage:[UIImage imageNamed:@"back_icon"] forState:UIControlStateNormal];
    };
    [self presentViewController:imagePickController animated:YES completion:nil];
}

#pragma mark- UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<UIImagePickerControllerInfoKey, id> *)editingInfo {
    [picker dismissViewControllerAnimated:YES completion:nil];
    SCCarAddImageItemModel *addModel = _imgArray.lastObject;
    if (addModel.isAddButton) {
        [_imgArray removeLastObject];
    }
    SCCarAddImageItemModel *model = [[SCCarAddImageItemModel alloc] init];
    model.image = image;
    [_imgArray addObject:model];
    [_imgArray addObject:addModel];
    [self.collectionView reloadData];
}

#pragma mark- TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    SCCarAddImageItemModel *addModel = _imgArray.lastObject;
    if (addModel.isAddButton) {
        [_imgArray removeLastObject];
    }
    for (NSInteger index = 0; index < assets.count; index++) {
        PHAsset *asset = assets[index];
        SCCarAddImageItemModel *model = [[SCCarAddImageItemModel alloc] init];
        model.asset = asset;
        model.image = photos[index];
        [_imgArray addObject:model];
    }
    [_imgArray addObject:addModel];
    [self.collectionView reloadData];
}

#pragma mark-
#pragma mark- UICollectionView
-(CGRect)collectionViewFrame {
    return CGRectMake(0, HeaderHeight, kSCScreenWidth, kSCScreenHeight-kSCNavigationHeight-kSCScreenBottomOffset-SegmentHeight-HeaderHeight);
}
-(void)configureCollectionView {
  
    [self.collectionView registerClass:[SCMaintUploadPdfHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SCMaintUploadPdfHeaderView"];
    [self.collectionView registerClass:[SCMaintUploadUrlHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SCMaintUploadUrlHeaderView"];
    
    [self registerNibHeaderName:@"SCComplaintHeaderView"];
    [self registerNibCellName:@"SCMaintUploadCollecCell"];
}

- (UICollectionViewLayout *)collectionViewLayout {
    SCCollectionViewColorFlowLayout *flow = [[SCCollectionViewColorFlowLayout alloc] init];
    flow.sectionBgColor = [UIColor whiteColor];
    flow.leftFloat = YES;
    flow.minimumLineSpacing = 10;
    flow.minimumInteritemSpacing = 10;
    return flow;
}
#pragma mark- UICollectionDelegate  UICollectionDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataSource.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    SCFormSectionModel *sectionModel = self.dataSource[section];
    if (section == _selectIndex) {
        if ([sectionModel.sectionKey isEqualToString:@"img"]) {
            return MIN(_imgArray.count,_maxCount);
        }else{
            return 0;
        }
    }else{
        return 0;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SCMaintUploadCollecCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SCMaintUploadCollecCell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.indexPath = indexPath;
    cell.model = _imgArray[indexPath.row];
    cell.imageView.layer.cornerRadius = 4;
    cell.imageView.layer.masksToBounds = YES;
    return cell;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    SCFormSectionModel *sec = self.dataSource[section];
    if ([sec.sectionKey isEqualToString:@"img"]) {
        return UIEdgeInsetsMake(0, 10, 15, 10);
    } else {
        return UIEdgeInsetsZero;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    SCFormSectionModel *sec = self.dataSource[indexPath.section];
    if ([sec.sectionKey isEqualToString:@"img"]) {
        CGFloat w = floorf((kSCScreenWidth - 50)/4);
        return CGSizeMake(w, w);
    }
    return CGSizeZero;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    SCFormSectionModel *sectionModel = self.dataSource[indexPath.section];
    WEAKSELF;
    if ([sectionModel.sectionKey isEqualToString:@"url"]) {
        SCMaintUploadUrlHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"SCMaintUploadUrlHeaderView" forIndexPath:indexPath];
        header.textFiled.text = _reportUrl;
        header.textFiled.placeholder = _uploadType == SCReportUploadMaintenance ? @"请输入维保报告链接" : @"请输入车辆检测报告链接";
        header.textChangeBlock = ^(NSString * _Nonnull text) {
            weakSelf.reportUrl = text;
        };
        return header;
    }else if ([sectionModel.sectionKey isEqualToString:@"img"]) {
        SCComplaintHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"SCComplaintHeaderView" forIndexPath:indexPath];
        header.topConstraint.constant = 3;
        SCFormSectionModel *sec = self.dataSource[indexPath.section];
        header.titleLabel.text = sec.headerTitle;
        header.titleLabel.font = SC_FONT(14);
        header.titleLabel.textColor = [UIColor blackColor];
        header.backgroundColor = [UIColor whiteColor];
        header.sepatorLine.hidden = YES;
        header.valueSwitch.hidden = YES;
        return header;
    }else{
        WEAKSELF;
        SCMaintUploadPdfHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"SCMaintUploadPdfHeaderView" forIndexPath:indexPath];
        header.pdfModel = _pdfModel;
        header.clickBlock = ^{
            [weakSelf pdfClick];
        };
        header.previewBlock = ^{
            [weakSelf previewClick];
        };
        header.deleteBlock = ^{
            [weakSelf deleteClick];
        };
        return header;
    }
    
    return nil;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    SCFormSectionModel *sectionModel = self.dataSource[section];
    return CGSizeMake(kSCScreenWidth, sectionModel.headerHeight);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SCFormSectionModel *sec = self.dataSource[indexPath.section];
     if ([sec.sectionKey isEqualToString:@"img"]) {
        SCCarAddImageItemModel *itemModel = _imgArray[indexPath.row];
        if (itemModel.isAddButton) {
            [self showActionSheet];
        }else{
            NSMutableArray *photos = [NSMutableArray arrayWithCapacity:0];
            MJPhotoBrowser *photoBrowser = [[MJPhotoBrowser alloc] init];
            for (SCCarAddImageItemModel *itemModel in _imgArray) {
                if (!itemModel.isAddButton) {
                    MJPhoto *photo = [[MJPhoto alloc] init];
                    if (itemModel.image) {
                        photo.image = itemModel.image;
                    }else{
                        photo.url = [NSURL URLWithString:sc_url_img(itemModel.imageUrlPath)];
                    }
                    [photos addObject:photo];
                }
            }
            photoBrowser.photos = photos;
            photoBrowser.currentPhotoIndex = indexPath.row;
            [photoBrowser show];
        }
    }

}
#pragma mark- SCMaintUploadCollecCellDelegate
-(void)deleteImageAtIndexPath:(NSIndexPath *)indexPath {
    [_imgArray removeObjectAtIndex:indexPath.item];
    [self.collectionView reloadData];
}

#pragma mark- uploadBtn
- (UIButton *)uploadBtn {
    if (!_uploadBtn) {
        _uploadBtn = [[UIButton alloc] init];
        [_uploadBtn setTitle:@"确认上传" forState:0];
        [_uploadBtn setTitleColor:SC_TextBlack_Primary forState:0];
        _uploadBtn.backgroundColor = SC_Color_Tint;
        [_uploadBtn addTarget:self action:@selector(uploadButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _uploadBtn.layer.cornerRadius = 23;
        _uploadBtn.layer.masksToBounds = YES;
        [_uploadBtn.titleLabel setFont:SC_FONT(14)];
    }
    return _uploadBtn;
}

#pragma mark- 点击上传pdf按钮
- (void)pdfClick{
    
    if (@available(iOS 11.0, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
    }
    
    [self presentViewController:self.documentPickerVC animated:YES completion:nil];
}

#pragma mark- 点击预览pdf
- (void)previewClick{

  SCWebViewController *web = [[SCWebViewController alloc] init];
    if (_pdfModel.reportPdf.length>0) {
      web.urlPath = _pdfModel.reportPdf;
    }
    if (_pdfModel.md5filePath.length>0) {
      web.urlPath = _pdfModel.md5filePath;
    }
    [self.navigationController pushViewController:web animated:YES];
}

#pragma mark- 点击删除pdf
- (void)deleteClick{
    _pdfModel = [SCReportPdfModel new];
    _pdfModel.showFile = NO;
    [SCFileManager deletePDFFile:_uploadType];
    [self.collectionView reloadData];
}

//懒加载
- (UIDocumentPickerViewController *)documentPickerVC {
    if (!_documentPickerVC) {
        NSArray * arr= @[@"com.adobe.pdf"];
        
        self.documentPickerVC = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:arr inMode:UIDocumentPickerModeOpen];
        self.documentPickerVC.edgesForExtendedLayout = UIRectEdgeNone;
        //设置代理
        _documentPickerVC.delegate = self;
        //设置模态弹出方式
        _documentPickerVC.modalPresentationStyle = UIModalPresentationFullScreen;
    }
    return _documentPickerVC;
}

#pragma mark - UIDocumentPickerDelegate

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    //获取授权
    BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
    if (fileUrlAuthozied) {
        //通过文件协调工具来得到新的文件地址，以此得到文件保护功能
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;

        [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
            //读取文件
            NSString *fileName = [newURL lastPathComponent];
            NSError *error = nil;
            NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
            _pdfModel.fileName = fileName;
            
            if (error) {
                //读取出错
            } else {
                _pdfModel.md5filePath = [SCFileManager storePdfFile:fileName uploadType:_uploadType fileData:fileData];
                _pdfModel.fileData = fileData;
                _pdfModel.showFile = YES;
                [self.collectionView reloadData];
                //判断服务器是否已经存在该文件
                [SCFileManager pdfExistUploaded:_pdfModel.md5filePath uploadType:_uploadType completion:^(NSString *fileURL) {
                    if (fileURL.length) {
                        _pdfModel.reportPdf = fileURL;
                        _pdfModel.md5filePath = @"";
                        _pdfModel.fileData = [NSData new];
                    }else{
                        _pdfModel.reportPdf = @"";
                    }
                }];
            }
            [self dismissViewControllerAnimated:YES completion:NULL];
        }];
        [urls.firstObject stopAccessingSecurityScopedResource];
    } else {
        //授权失败
    }
    if (@available(iOS 11.0, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
}

- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller{
    if (@available(iOS 11.0, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
}

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url{
    if (@available(iOS 11.0, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
}

- (SCDynamicSegmentView *)segmengView{
    if(!_segmengView){
        SCDynamicSegmentView *segmentView = [[SCDynamicSegmentView alloc] initWithFrame:CGRectMake(0, 0, kSCScreenWidth, SegmentHeight)];
        segmentView.delegate = self;
        segmentView.hiddenBottomLine = YES;
        segmentView.clipsToBounds = YES;
      segmentView.itemWidth = _uploadType == SCReportUploadCarContract ? (kSCScreenWidth-20*2)/2:(kSCScreenWidth-20*2)/3;
        _segmengView = segmentView;
        
        [self.view addSubview:segmentView];
    }
    return _segmengView;
}
#pragma mark - 选项卡点击切换
- (void)segmentDidClickedAtIndex:(NSInteger)index{
    _selectIndex = index;
    [self.segmengView selectedAtIndex:MAX(0, _selectIndex)];
    [self.dataSource enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SCFormSectionModel *model = (SCFormSectionModel *)obj;
        if (index != idx) {
            model.headerHeight = 0;
        }else{
            model.headerHeight = [self.headerHeight[idx] intValue];
        }
    }];
    [self.collectionView reloadData];
}

- (void)dealloc{
    
}

@end
